package com.apexwear.apexutils.utils;

import android.content.Context;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.apexwear.apexutils.R;
import com.apexwear.apexutils.common.Constant;
import com.apexwear.apexutils.data.DeviceInfo;
import com.apexwear.apexutils.model.Ota;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUtils {
    static final String TAG = "FileUtils";

    /**
     * 创建OTA保存目录
     *
     * @param mContext
     * @return
     */
    public static boolean createDir(Context mContext) {
        String cachePath = getDirPath(mContext);
        if (TextUtils.isEmpty(cachePath)) {
            return false;
        }
        File dirFile = new File(cachePath);
        if (!dirFile.exists()) {
            return dirFile.mkdirs();
        } else {
            if (dirFile.isFile()) {
                dirFile.delete();
                return dirFile.mkdirs();
            }
            return true;
        }

    }

    public static String getDirPath(Context mContext) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                cachePath = mContext.getApplicationContext().getExternalFilesDir(mContext.getApplicationContext().getString(R.string.app_name)).getAbsolutePath();
            } else {
                cachePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + mContext.getApplicationContext().getString(R.string.app_name);
            }
        } else {
            cachePath = Environment.getRootDirectory().toString() + "/" + mContext.getApplicationContext().getString(R.string.app_name);
        }
        return cachePath;
    }

    public static String getDownPath(Context mContext) {
        String downPath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                downPath = mContext.getApplicationContext().getExternalFilesDir(mContext.getString(R.string.change_id)).getAbsolutePath();
            } else {
                downPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
            }
        } else {
            downPath = Environment.getRootDirectory().toString() + "/" + Environment.DIRECTORY_DOWNLOADS;
        }
        return downPath;
    }

    public static boolean saveFile(String fileName, Context mContext, String srcFile) {
        String fileDir = getDirPath(mContext);
        File f = new File(fileDir, fileName);
        if (f.mkdirs()) {
            try {
                FileChannel fileInputStream = new FileInputStream(srcFile).getChannel();
                FileChannel fileOutputStream = new FileOutputStream(f).getChannel();
                fileOutputStream.transferFrom(fileInputStream, 0, fileInputStream.size());
                fileOutputStream.close();
                fileInputStream.close();
                return true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }

        } else {
            return false;
        }
    }

    public static List<Ota> getOtaFile(Context mContext) {
        String cachePath = getDirPath(mContext);
        if (TextUtils.isEmpty(cachePath)) {
            return null;
        }
        File dirFile = new File(cachePath);
        if (!dirFile.exists()) {
            return null;
        } else {
            if (dirFile.isFile()) {
                return null;
            }
            File[] fileList = dirFile.listFiles();
            if (fileList == null) {
                return null;
            }
            List<Ota> otaList = new ArrayList<>();
            List<DeviceInfo> infos = getWatchNameWithSN(mContext);
            for (File f : fileList) {
                if (f.exists() && f.isDirectory()) {
                    continue;
                }
                Ota ota = new Ota();
                String fileName = f.getName();
                Log.e(TAG, "文件名:" + fileName);

                ota.setFileName(fileName);
                ota.setFilePath(f.getAbsolutePath());
                if (fileName.contains("_")) {
                    String[] typeArray = fileName.split("_");
                    ota.setWatchType(typeArray[0]);
                    for (DeviceInfo info : infos) {
                        if (info.deviceNum.equalsIgnoreCase(typeArray[0])) {
                            ota.setWatchName(info.deviceName);
                            break;
                        }
                    }

                    Log.e(TAG, "比对的数据:" + typeArray[1]);
                    if (typeArray[1].toLowerCase().contains("his")) {
                        ota.setFileType("his");
                        if (typeArray[1].contains("zip")) {
                            int index = typeArray[1].lastIndexOf("zip");
                            String version = typeArray[1].toUpperCase().substring(0, index - 1).split("-")[1];
                            Log.e(TAG, "his版本信息:" + version + ",总的信息:" + typeArray[1]);
                            if (typeArray[1].contains("-")) {
                                ota.setOtaVersion(version);
                            }
                        } else {
                            Log.e(TAG, "不包含zip");
                            if (typeArray[1].contains("-")) {
                                ota.setOtaVersion(typeArray[1].toUpperCase().split("-")[1]);
                            }
                        }


                    } else if (typeArray[1].contains("R")) {
                        ota.setFileType("Res");
                        if (typeArray[1].contains("bin") || typeArray[1].contains("ufw")) {
                            int index = 0;
                            if (typeArray[1].contains("bin")) {
                                index = typeArray[1].lastIndexOf("bin");
                            } else {
                                index = typeArray[1].lastIndexOf("ufw");
                            }
                            ota.setOtaVersion(typeArray[1].toUpperCase().substring(0, index == -1 ? typeArray[1].length() : index - 1));
                        } else {
                            ota.setOtaVersion(typeArray[1].toUpperCase());
                        }

                    } else if (typeArray[1].contains("AP")) {
                        ota.setFileType("Apollo");
                        if (typeArray[1].contains("bin") || typeArray[1].contains("ufw")) {
                            int index = 0;
                            if (typeArray[1].contains("bin")) {
                                index = typeArray[1].lastIndexOf("bin");
                            } else {
                                index = typeArray[1].lastIndexOf("ufw");
                            }

                            ota.setOtaVersion(typeArray[1].toUpperCase().substring(0, index == -1 ? typeArray[1].length() : index - 1));
                        } else {
                            ota.setOtaVersion(typeArray[1].toUpperCase());
                        }
                    } else if (typeArray[1].contains("T")) {
                        ota.setFileType("Tp");
                        if (typeArray[1].contains("bin") || typeArray[1].contains("ufw")) {
                            int index = 0;
                            if (typeArray[1].contains("bin")) {
                                index = typeArray[1].lastIndexOf("bin");
                            } else {
                                index = typeArray[1].lastIndexOf("ufw");
                            }
                            ota.setOtaVersion(typeArray[1].toUpperCase().substring(0, index == -1 ? typeArray[1].length() : index - 1));
                        } else {
                            ota.setOtaVersion(typeArray[1].toUpperCase());
                        }
                    } else if (typeArray[1].contains("H")) {
                        ota.setFileType("Hr");
                        if (typeArray[1].contains("bin") || typeArray[1].contains("ufw")) {
                            int index = 0;
                            if (typeArray[1].contains("bin")) {
                                index = typeArray[1].lastIndexOf("bin");
                            } else {
                                index = typeArray[1].lastIndexOf("ufw");
                            }
                            ota.setOtaVersion(typeArray[1].toUpperCase().substring(0, index == -1 ? typeArray[1].length() : index - 1));
                        } else {
                            ota.setOtaVersion(typeArray[1].toUpperCase());
                        }
                    } else if (typeArray[1].contains("U")) {
                        ota.setFileType("Dial");
                    } else if (typeArray[1].contains("S")) {
                        ota.setFileType("Smt");
                        if (typeArray[1].contains("bin") || typeArray[1].contains("ufw")) {
                            int index = 0;
                            if (typeArray[1].contains("bin")) {
                                index = typeArray[1].lastIndexOf("bin");
                            } else {
                                index = typeArray[1].lastIndexOf("ufw");
                            }
                            ota.setOtaVersion(typeArray[1].toUpperCase().substring(0, index == -1 ? typeArray[1].length() : index - 1));
                        } else {
                            ota.setOtaVersion(typeArray[1].toUpperCase());
                        }
                    } else if (typeArray[1].contains("G")) {
                        ota.setFileType("Gps");
                    }

                } else {
                    if ((fileName.startsWith("watch") || fileName.startsWith("WATCH")) && fileName.length() >= 7) {
                        ota.setFileType("Dial");
                        ota.setWatchName("iTOUCH AIR 5 PRO");
                        ota.setWatchType("002086");
                    }
                }
                Log.e(TAG, "OTA信息:" + ota.toString());
                otaList.add(ota);
            }
            return otaList;
        }

    }

    private static List<DeviceInfo> getWatchNameWithSN(Context mContext) {
        List<DeviceInfo> infos = null;
        try {
            InputStream inputStream = mContext.getAssets().open("device.json");
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
                BufferedReader reader = new BufferedReader(inputStreamReader);
                StringBuilder readJson = new StringBuilder();
                String tempString;
                while ((tempString = reader.readLine()) != null) {
                    readJson.append(tempString);
                }
                infos = JSONArray.parseArray(readJson.toString(), DeviceInfo.class);
                reader.close();
                inputStreamReader.close();
                inputStream.close();

            }
        } catch (Exception e) {

        }
        return infos;
    }

    public static String getLogPath(Context mContext) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                cachePath = mContext.getApplicationContext().getExternalFilesDir("log").getAbsolutePath();
            } else {
                cachePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/log";
            }
        } else {
            cachePath = Environment.getRootDirectory().toString() + "/log";
        }
        return cachePath;
    }

    public static boolean saveHeartLog(String content, Context mContext) {

        File f = createFile(mContext, "heart_log.txt");
        if (f == null) {
            return false;
        }

        try {
            Writer out = new FileWriter(f, false);
            out.write(content + "\r\n");
            out.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    public static boolean createLogDir(Context mContext) {
        String logPath = getLogPath(mContext);
        if (TextUtils.isEmpty(logPath)) {
            return false;
        }
        File dir = new File(logPath);
        if (!dir.exists()) {
            return dir.mkdirs();
        } else {
            if (dir.isFile()) {
                dir.delete();
                return dir.mkdirs();
            }
            return true;

        }
    }

    public static File createFile(Context mContext, String fileName) {
        boolean dir = createLogDir(mContext);
        if (!dir) {
            return null;
        }
        File f = new File(getLogPath(mContext), fileName);
        if (!f.exists()) {
            try {
                f.createNewFile();
                return f;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        return f;
    }
}
